<?php

/**
 * SSO单点登录同步
 * File Name：TongbuSSO.php
 * File Encoding：UTF-8
 * File New Time：2014-10-23 13:56:05
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class TongbuSSO {

    //通知地址
    protected $jsUrl = '';
    //标识符
    protected $key = '__tongbu__';
    //配置信息
    protected $config = array(
        'client_id' => 1, //站点id
        'client_key' => 'FIv2v8ivfUY6WUGIfzKr7Vfn4L7qQ5VFVGvF4NtF3Dg0Hx3Hy2SoR3', //站点密钥
        'key_validity' => 3000, //密文有效期，单位秒
    );

    /**
     * 链接同步服务
     * @staticvar null $handier
     * @return \TongbuDz
     */
    static public function getInstance() {
        static $handier = NULL;
        if (empty($handier)) {
            $handier = new self();
        }
        return $handier;
    }

    /**
     * 同步登录dz
     * @param type $user 用户信息
     * @return boolean
     */
    public function login($user) {
        if (empty($user)) {
            return false;
        }
        Yii::import('ext.SsoClient.*');
        $js = Client::getInstance($this->config)->user_synlogin($user['uid']);
        Yii::app()->session->add($this->key, $js);
        return true;
    }

    /**
     * 同步退出DZ
     * @return boolean
     */
    public function logout() {
        Yii::import('ext.SsoClient.*');
        $js = Client::getInstance($this->config)->user_synlogout();
        Yii::app()->session->add($this->key, $js);
        return true;
    }

    /**
     * 同步更新资料
     * @param type $username 用户名
     * @param type $data 需要更新的数据
     * @param type $newpw 新密码，为空不修改
     * @return boolean
     */
    public function user_edit($username, $data = array(), $newpw = '') {
        Yii::import('ext.SsoClient.*');
        return Client::getInstance($this->config)->user_edit($username, $data, $newpw);
    }

    /**
     * 同步删除用户
     * @param type $username 用户名
     * @param type $isuid
     * @return type
     */
    public function user_delete($username, $isuid = 0) {
        Yii::import('ext.SsoClient.*');
        return Client::getInstance($this->config)->user_delete($username, $isuid);
    }

    /**
     * 执行同步
     */
    public function sendTongbu() {
        $tongbu = Yii::app()->session[$this->key];
        Yii::app()->session->remove($this->key);
        if (!empty($tongbu)) {
            return $tongbu;
        }
        return '';
    }

}
